package com.joelaws.prototype.server.dao;

import gnu.trove.TLongObjectHashMap;

import java.util.ArrayList;
import java.util.List;

import com.joelaws.prototype.client.data.Message;
import com.joelaws.prototype.client.data.User;

public class MessagingDAO {

	private TLongObjectHashMap<ArrayList<Message>> fromCache;

	private TLongObjectHashMap<ArrayList<Message>> toCache;

	protected MessagingDAO() {
		fromCache = new TLongObjectHashMap<ArrayList<Message>>();
		toCache = new TLongObjectHashMap<ArrayList<Message>>();
	}

	public synchronized List<Message> getFromMessages(User user) {
		return getFromMessages(user.getUserID());
	}

	public synchronized List<Message> getFromMessages(long userID) {
		return fromCache.get(userID);
	}

	public synchronized List<Message> getToMessages(User user) {
		return getToMessages(user.getUserID());
	}

	public synchronized List<Message> getToMessages(long userID) {
		return toCache.get(userID);
	}

	public synchronized void store(Message message) {
		ArrayList<Message> messages;

		messages = fromCache.get(message.getFromUser());
		if (messages == null) {
			messages = new ArrayList<Message>();
		}
		messages.add(message);
		fromCache.put(message.getFromUser(), messages);

		messages = toCache.get(message.getToUser());
		if (messages == null) {
			messages = new ArrayList<Message>();
		}
		messages.add(message);
		toCache.put(message.getToUser(), messages);

	}

	public synchronized void removeService(long userID) {
		fromCache.remove(userID);
	}
}
